package com.goddess.yeecolor.tools;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;

import com.goddess.yeecolor.R;

import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * 升级
 */
public class VersionTools {
    // 更新应用版本标记
    private static final int UPDARE_TOKEN = 0x29;
    // 准备安装新版本应用标记
    private static final int INSTALL_TOKEN = 0x31;
    // 进度条的当前刻度值
    private int curProgress;
    private static final String FILE_PATH = Environment.getExternalStorageDirectory() + File.separator +"autoupdate" + File.separator;
    // 下载应用存放全路径
    private static final String FILE_NAME = FILE_PATH + "autoupdate.apk";
    private boolean isCancel;
    private Dialog dialog;
    private static Context mContext;
    private ProgressBar mProgress;
    private int vercode;
    private String down;
    private String jsonString;
    public static VersionTools version;
    public static VersionTools getIntence(){

        if (version==null){
            version=new VersionTools();
        }
        return version;
    }
    /**
     * 获取版本号
     */

    public void getVersionNumber(Context mContext){
        this.mContext=mContext;
        try {
            PackageManager manager=mContext.getPackageManager();
            PackageInfo info=manager.getPackageInfo(mContext.getPackageName(),PackageManager.GET_CONFIGURATIONS);
            vercode=info.versionCode;

            Map<Object,Object>map=new HashMap<>();
            OkttpUtils.getIntence().OkttpPost(MyUrl.VERSION,map,handler,1);
        }
        catch (Exception e){
            e.printStackTrace();
        }

    }

    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            try {
                jsonString=msg.getData().getString("result");
                JSONObject result=new JSONObject(jsonString);

                int code=result.getInt("code");
                if (code==100){
                    JSONObject res=result.getJSONObject("result");
                    int ver=res.getInt("ver");
                    down=res.getString("down");

                    if (vercode<ver){
                        showDialog();
                    }
                    else {
                        ToastUtils.toast("当前已是最新版本");
                    }
                }
            }
            catch (Exception e){
                e.printStackTrace();
            }
        }
    };
    private Handler handlers=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case UPDARE_TOKEN://设置进度
                    mProgress.setProgress(curProgress);
                    break;
                case INSTALL_TOKEN://下载完成
                    installApp();
                    break;
            }
        }
    };
    private String message = "检测到本程序有新版本发布，建议您更新！";

    /**
     * 弹出升级按钮
     */
    private void showDialog(){
        new AlertDialog.Builder(mContext).setTitle("版本更新").setMessage(message).setPositiveButton("升级", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.dismiss();
            }
        }).setNegativeButton("忽略", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.dismiss();
            }
        }).create().show();
    }

    /**
     * 下载弹窗
     */
    private void showDownProgress(){
        View view= LayoutInflater.from(mContext).inflate(R.layout.down_prograss,null);
        mProgress= (ProgressBar) view.findViewById(R.id.down_progressBars);
        AlertDialog.Builder builder=new AlertDialog.Builder(mContext);
        builder.setTitle("版本更新中");
        builder.setView(view);
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                isCancel = true;
            }
        });
        dialog = builder.create();
        dialog.show();
    }
    /**
     * 下载下载开始
     */

    public void downloadApp(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                URL url=null;
                HttpURLConnection connection;
                FileOutputStream out = null;
                InputStream in = null;
                try{
                    url=new URL(down);
                    connection= (HttpURLConnection) url.openConnection();
                    connection.connect();
                    long length=connection.getContentLength();//长度
                    in=connection.getInputStream();
                    File file=new File(FILE_PATH);
                    if (!file.exists()){
                        file.mkdir();
                    }
                    out=new FileOutputStream(new File(FILE_NAME));
                    byte[]buffer=new byte[1024];
                    int len=0;
                    long readedLength=01 ;
                    while ((len=in.read())!=-1){
                        // 用户点击“取消”按钮，下载中断
                        if(isCancel) {
                            break;
                        }
                        out.write(buffer,0,len);
                        readedLength += len;
                        curProgress = (int) (((float) readedLength /length) * 100);
                        handlers.sendEmptyMessage(UPDARE_TOKEN);
                        if(readedLength >=length) {
                            dialog.dismiss();
                            // 下载完毕，通知安装
                            handlers.sendEmptyMessage(INSTALL_TOKEN);
                            break;
                        }
                    }
                    out.flush();//刷新
                    out.close();//关闭输出
                    in.close();//关闭输入流
                    connection.disconnect();//中断连接
                }
                catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();
    }
    /**
     * 安装新版本应用
     */
    public void installApp() {
        File appFile = new File(FILE_NAME);
        if(!appFile.exists()) {
            return;
        }
        // 跳转到新版本应用安装页面
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.parse("file://" + appFile.toString()), "application/vnd.android.package-archive");
        mContext.startActivity(intent);
    }
}
